package hsp.admin.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import hsp.admin.util.SessionUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;
import java.util.function.Supplier;


@Component
public class MyBatisPlusMetaObjectConfig implements MetaObjectHandler {

    private final SessionUtil sessionUtil;

    @Autowired
    public MyBatisPlusMetaObjectConfig(
        SessionUtil sessionUtil
    ){
        this.sessionUtil = sessionUtil;
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "creator", String.class, sessionUtil.getUsername());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "modifyTime", LocalDateTime.class, LocalDateTime.now());
        this.strictUpdateFill(metaObject, "modifier", String.class, sessionUtil.getUsername());
    }

    /**
     * ***解决*** 修改人和修改时间有值后不更新的问题
     * 重写，数据有值不更新改为数据有值也要更新。
     */
    @Override
    public MetaObjectHandler strictFillStrategy(MetaObject metaObject, String fieldName, Supplier<?> fieldVal) {
        Object obj = fieldVal.get();
        if (Objects.nonNull(obj)) metaObject.setValue(fieldName, obj);
        return this;
    }

}
